import { Reducer, Subscription, Effect, history } from 'umi';
import { queryCurrentUser } from '@/utils';

export interface UserModelState {
    token: string;
    userid: number;
    openid: string;
}

export interface UserModelType {
    namespace: 'user';
    state: UserModelState;
    reducers: {
        save: Reducer<UserModelState>;
    };
    effects: {
        query: Effect;
    };
    subscriptions?: { setup: Subscription };
}

const UserModel: UserModelType = {
    namespace: 'user',
    state: {
        token: '',
        userid: 0,
        openid: '',
    },
    // state: { token: '', userid: '', openid: '' },
    reducers: {
        save(state, action) {
            return {
                ...state,
                ...action.payload,
            };
        },
    },
    effects: {
        *query(_, { call, put }) {
            const response = yield call(queryCurrentUser);
            yield put({
                type: 'save',
                payload: response,
            });
            if (response) {
                history.push('/order_list');
            }
        },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname }) => {
                if (pathname === '/login') {
                    dispatch({
                        type: 'query',
                    });
                }
            });
        },
    },
};

export default UserModel;
